package com.shu.juc;

import lombok.extern.slf4j.Slf4j;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2020/7/31 11:06
 */
@Slf4j
public class WaitNotifyTest {
    private int number = 0;

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyTest waitNotifyTest = new WaitNotifyTest();


        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    waitNotifyTest.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"减法").start();


        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    waitNotifyTest.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"加法").start();


        log.info(String.valueOf(waitNotifyTest.number));
    }

    public synchronized void incr() throws InterruptedException {
        while (number != 0) {
            this.wait();
        }
        ++number;
        log.info("");
        this.notifyAll();
    }

    public synchronized void decr() throws InterruptedException {
        while (number == 0) {
            this.wait();
        }
        --number;
        log.info("");
        this.notifyAll();
    }
}
